package com.itheima.interceptor;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author: zhengsuyang
 * @Desc:
 * @create: 2025-09-12 17:54
 **/
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    /**
     *
     * @param request
     * @param response
     * @param handler
     * @return ture：放行  false: 拦截
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 资源执行前执行一次
        log.info("执行preHandle.....");
        // 1.从请求头获取token
        String token = request.getHeader("token");
        // 2.解析token
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer userId = claims.get("id", Integer.class);
            CurrentHolder.setUserId(userId);
        } catch (Exception e) {
            // 1.解析不通过 直接返回401
            log.info("解析令牌失败, 返回错误结果");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        // 2.通过直接放行
        log.info("令牌合法, 放行");
        return true; // 放行
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 资源页面渲染
        // 移除资源
        CurrentHolder.removeUserId();
    }
}
